package chapter14;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author : DuJiabao
 * @Date : 2021/2/25 15:33
 * @Project : thinking_in_java
 * @File : null.java
 * @Desc :
 */

class DynamicProxyHandler implements InvocationHandler {
  private Object proxied;

  public DynamicProxyHandler(Object proxied) {
    this.proxied = proxied;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("**** proxy: " + proxy.getClass() + ". method: " + method + ", args: " + args); // args输出对象的信息
    if (args != null) {
      for (Object arg : args) {
        System.out.println(arg + " ");
      }
    }
    return method.invoke(proxied, args);
  }
}

public class SimpleDynamicProxy {
  public static void consumer(Interface iface) {
    iface.doSomething();
    iface.SomethingElse("bonobo");
  }

  public static void main(String[] args) {
    RealObject real = new RealObject();
    consumer(real);
    Interface proxy = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[]{Interface.class}, new DynamicProxyHandler(real));
    consumer(proxy);
  }
}



